﻿namespace UFIDA.U9.Cust.STR.SyncSV
{
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    using System.ServiceModel.Channels;
    using System.Text;
    using UFIDA.U9.Base.Organization;
    using UFIDA.U9.CBO.HR.Department;
    using UFIDA.U9.Cust.STR.SyncSV.Dtos;
    using UFIDA.U9.Cust.STR.SyncSV.Public;
    using UFSoft.UBF.AopFrame;
    using UFSoft.UBF.Business;
    using UFSoft.UBF.Util.Context;
    using UFSoft.UBF.Util.DataAccess;

    /// <summary>
    /// OADepartmentSyncService partial 
    /// </summary>	
    public partial class OADepartmentSyncService
    {
        internal BaseStrategy Select()
        {
            return new OADepartmentSyncServiceImpementStrategy();
        }
    }

    #region  implement strategy	
    /// <summary>
    /// Impement Implement
    /// 
    /// </summary>	
    internal partial class OADepartmentSyncServiceImpementStrategy : BaseStrategy
    {
        public OADepartmentSyncServiceImpementStrategy() { }

        public override object Do(object obj)
        {
            OADepartmentSyncService bpObj = (OADepartmentSyncService)obj;
            //检查数据是否为空，是否为首次获取
            DataAccessor.RunSQL(DataAccessor.GetConn(), $@"select top 1 SyncDate from Cust_OADepartment order by SyncDate desc", null, out DataSet countDS);
            string modifiedDate;
            if (countDS.Tables[0].Rows.Count == 0)
            {
                modifiedDate = $"{new DateTime(1970, 1, 1):yyyy-MM-dd HH:mm:ss}";
            }
            else
            {
                modifiedDate = $"{countDS.Tables[0].Rows[0][0]:yyyy-MM-dd HH:mm:ss}";
            }
            HttpHelper httpHelper = new HttpHelper();
            JsonConfig _config = new JsonConfig();
            var OAUrl = _config.SelectToken("OA.URL");
            httpHelper.URL = OAUrl + "/api/hrm/resful/getHrmdepartmentWithPage";
            var postPara = new
            {
                @params = new
                {
                    modified = modifiedDate,
                    pagesize = 999,
                    curpage = 1
                }
            };
            httpHelper.Content = JsonConvert.SerializeObject(postPara);
            httpHelper.OAGetToken();
            var postResult = httpHelper.Request();
            JObject jObject = JObject.Parse(postResult);
            JArray dataList = (JArray)jObject["data"]["dataList"];
            if (dataList.Count == 0)
                return null;
            StringBuilder sql = new StringBuilder("INSERT INTO Cust_OADepartment ( supdepid, departmentmark, departmentname, created, departmentcode, modified, id, subcompanyid1,UseFlag,SyncDate) VALUES ");
            List<OADepartment> departments = new List<OADepartment>();
            foreach (JObject item in dataList)
            {
                OADepartment department = new OADepartment();
                department.supdepid = Convert.ToInt32(item["supdepid"]);
                department.departmentmark = item["departmentmark"].ToString();
                department.departmentname = item["departmentname"].ToString();
                department.departmentcode = item["departmentcode"].ToString();
                department.created = Convert.ToDateTime(item["created"]);
                department.modified = Convert.ToDateTime(item["modified"]);
                department.subcompanyid1 = Convert.ToInt32(item["subcompanyid1"]);
                department.id = Convert.ToInt32(item["id"]);
                department.UseFlag = false;
                department.SyncDate = DateTime.Now;
                departments.Add(department);

                sql.Append($"( '{item["supdepid"]}', '{item["departmentmark"]}', '{item["departmentname"]}', '{item["created"]}', '{item["departmentcode"]}', '{item["modified"]}', '{item["id"]}', '{item["subcompanyid1"]}',0,getdate()),");
            }

            // Remove the last comma and add a semicolon
            sql.Length--;
            sql.Append(";");
            DataAccessor.RunSQL(DataAccessor.GetConn(), sql.ToString(), null);

            List<OADepartment> succList = new List<OADepartment>();
            var departmentsCodes = departments.Where(t => !string.IsNullOrEmpty(t.departmentcode)).Select(t => t.departmentcode).ToList();
            if (departmentsCodes.Count > 0)
            {
                Dictionary<int, string> valueToCodeMap = new Dictionary<int, string>
            {
                { 1, "02" },
                { 2, "01" },
                { 3, "04" },
                    {4,"03" }
            };
                var exsitDepartment = Department.Finder.FindAll($"Code in ({string.Join(",", departmentsCodes.Select(t => $"'{t}'"))})").Cast<Department>().ToList();
                List<Organization> orgs = Organization.Finder.FindAll("IsOperatingOrg = 1").Cast<Organization>().ToList();
                var departments1 = departments.Where(t => t.departmentcode.Length == 3);
                using (UFSoft.UBF.Business.ISession session = Session.Open())
                {
                    foreach (OADepartment department in departments1)
                    {
                        var org = orgs.FirstOrDefault(t => t.Code == valueToCodeMap[department.subcompanyid1]);
                        if (org != null)
                        {
                            var dept = exsitDepartment.FirstOrDefault(t => t.Code == department.departmentcode) ?? Department.Create();
                            dept.Code = department.departmentcode;
                            dept.Name = department.departmentname;
                            dept.Org = org;
                            succList.Add(department);
                        }
                    }
                    session.Commit();
                }
                var departments2 = departments.Where(t => t.departmentcode.Length == 5);
                using (UFSoft.UBF.Business.ISession session = Session.Open())
                {
                    foreach (OADepartment department in departments2)
                    {
                        var org = orgs.FirstOrDefault(t => t.Code == valueToCodeMap[department.subcompanyid1]);
                        if (org != null)
                        {
                            var dept = exsitDepartment.FirstOrDefault(t => t.Code == department.departmentcode) ?? Department.Create();
                            dept.Code = department.departmentcode;
                            dept.Name = department.departmentname;
                            dept.Org = org;
                            succList.Add(department);
                        }
                    }
                    session.Commit();
                }
            }
            if (succList.Count > 0)
            {
                string upSql = $@"update Cust_OADepartment set UseFlag = 1 where id in ({string.Join(",", succList.Select(t => t.id))}) and SyncDate >= DATEADD(MINUTE,-3,GETDATE())";
                DataAccessor.RunSQL(DataAccessor.GetConn(), upSql, null);
            }
            return "";
        }
    }

    #endregion


}